package com.blacamdk.ChatNetModule;

import com.ck.GUI.ChatFrame;
import com.ck.GUI.Main;

import java.awt.*;
import java.util.Vector;

import static com.ck.GUI.ChatFrame.infoPanel;
import static com.ck.GUI.ChatFrame.mainArea;

/**
 * syncWithServer
 *
 * @author BlacAmDK
 * @date 16-12-22
 */
public class syncWithServer implements Runnable{
    public static boolean flag = true;
    public syncWithServer() { }

    @Override
    public void run() {
        boolean needRepaint = false;
        while (flag)
        {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ignored) { }
            Vector<Message> message = ClientMain.recv();
            if(message == null) continue;
            for (Message m:message
                 ) {
                //处理每条消息
                if(m.getFrom() == ChatFrame.UIDTalking)
                    needRepaint = true;
                if(!Utils.addContent(m.getFrom(), m.getTime(), m.getContent(), false)) {
                    ChatFrame.onlineList.setEnabled(false);
                    ClientMain.updateUserList();
                    ChatFrame.onlineList.setEnabled(true);
                    Utils.addContent(m.getFrom(), m.getTime(), m.getContent(), false);
                }


            }
            if(needRepaint) {
                mainArea.setText("");
                mainArea.append(ClientMain.userVector.get(ClientMain.getIndexFromUsername(ChatFrame.usernameTalking)).Content);
                Point p = new Point();
                p.setLocation(0, mainArea.getLineCount() * 10);
                infoPanel.getViewport().setViewPosition(p);
            }
            needRepaint = false;
        }

    }

}
